#!/bin/sh /etc/rc.common
#
#SFE connection manager has a lower priority, it should be started after other connection manager
#to detect the existence of connection manager with higher priority

START=99

#load shortcut-fe connection manager
load_sfe_cm() {
	local kernel_version="$(uname -r)"

	#shortcut-fe-drv.ko is not needed because other connection manager is not enabled
	[ -d "/sys/module/shortcut_fe_drv" ] &&
		rmmod shortcut_fe_drv

	[ -e "/lib/modules/$kernel_version/shortcut-fe-cm.ko" ] &&
		[ ! -d /sys/module/shortcut_fe_cm ] &&
		insmod "/lib/modules/$kernel_version/shortcut-fe-cm.ko" &&
		return

	[ -e "/lib/modules/$kernel_version/fast-classifier.ko" ] &&
		[ ! -d /sys/module/fast_classifier ] &&
		insmod "/lib/modules/$kernel_version/fast-classifier.ko" &&
		return
}

unload_sfe() {
	[ -d /sys/module/shortcut_fe_cm ] &&
		rmmod shortcut_fe_cm

	[ -d /sys/module/fast_classifier ] &&
		rmmod fast_classifier

	rm -f /dev/sfe_ipv4 /dev/sfe_ipv6
}

load_sfe() {
	local enabled bridge ipv4_dev_num ipv6_dev_num offload_at_pkts
	config_load sfe
	config_get_bool enabled config enabled 0
	config_get_bool bridge config bridge 0
	config_get offload_at_pkts config offload_at_pkts 128

	unload_sfe

	[ "$enabled" -eq 1 ] || return
	[ -d "/sys/kernel/debug/ecm" ] && return

	load_sfe_cm

	echo "$bridge" >/sys/fast_classifier/skip_to_bridge_ingress
	echo "$offload_at_pkts" >/sys/fast_classifier/offload_at_pkts

	ipv4_dev_num=$(cat /sys/sfe_ipv4/debug_dev)
	[ -n "$ipv4_dev_num" ] &&
		mknod /dev/sfe_ipv4 c "$ipv4_dev_num" 0

	ipv6_dev_num=$(cat /sys/sfe_ipv6/debug_dev)
	[ -n "$ipv6_dev_num" ] &&
		mknod /dev/sfe_ipv6 c "$ipv6_dev_num" 0
}

start() {
	load_sfe
}

stop() {
	unload_sfe
}

restart() {
	start
}
